package com.hc.oauthserver.service;

import com.hc.oauthserver.mapper.UserMapper;
import com.hc.oauthserver.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service(value = "UserService")
public class UserService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        } else {
            //List<GrantedAuthority> client = AuthorityUtils.commaSeparatedStringToAuthorityList("client");
            return new User(user.getUsername(), passwordEncoder.encode(user.getPassword()), user.getRoles());
        }
    }
}